<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 */
class ShunfengpddController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merno'] = $this->config['mch_id'];
        switch($this->config['paytype']) {
            case 1:
                $data['bus_no'] = '0101';
                break;
            //支付宝
            case 3:
            case 4:
            case 17:
            case 18:
                $data['bus_no'] = '0206';
                break;
				//银联扫码
            case 11:
                $data['bus_no'] = '0701';
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
		
        $data['amount'] = intval($return['amount']*100);
        $data['goods_info'] = 'nvc';
        $data['order_id'] = $return['orderid'];
        $data['return_url'] = $return['callbackurl'];
        $data['notify_url'] = $return['notifyurl'];
		
		
		
		$post = [];
		$post['requestId'] = $return['orderid'];
		$post['orgId'] = $return['appid'];
		$post['timestamp'] = date("YmdHis",time());
		$post['productId'] = '0100';
		$post['businessData'] = json_encode($data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
		$post['dataSignType'] = '0';
		$post['signData'] = $this->getSign($post);
		
		$res = curl($this->config['gateway'], httpstr($post));

		$res = json_decode($res, true);
		
		$result = json_decode($res['result'], true);
		$code = '';
		if($result){
			$code = $result['url'];
		}

		if(!$code){
			if($res['msg']){
				$this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
			}
			
			$this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		$paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                if(isMobile()){
                    header("Location:{$code}"); exit;
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

	private function getSign($data){
		ksort($data);
		$str = "";
		
		foreach($data as $k=>$v){
			if($k ==='signData' || $v===''){
				continue;
			}
			
			$str .= "{$k}={$v}&";
		}
		
		$str = substr($str,0,-1) . $this->config['signkey'];
		
		//echo '<pre/>'; print_r($data); echo "签名串：". $str . "<br/><br/>";
		//file_put_contents("a.txt", $str);
		
		return strtoupper(md5($str));
	}

	private function getSign2($data){
		ksort($data);
		$str = "";
		
		foreach($data as $k=>$v){
			if($k ==='sign_data' || $v===''){
				continue;
			}
			
			$str .= "{$k}={$v}&";
		}
		
		$str = substr($str,0,-1) . $this->config['signkey'];
		
		//echo '<pre/>'; print_r($data); echo "签名串：". $str . "<br/><br/>";
		//file_put_contents("a.txt", $str);
		
		return md5($str);
	}
	
    //通知
    public function notifyurl(){
        //$this->debug_callback();

        if(!$this->checkip(getIP(),['149.129.69.73'])){
            exit("wrong");
        }
		
		$p = I("post.");
		/* $p = array (
		  'amount' => '5000',
		  'goods_info' => 'nvc',
		  'merno' => '372019340400011995',
		  'order_id' => '2019010421535234161',
		  'orgid' => '3720193404000129',
		  'plat_order_id' => '2019010421535379363121',
		  'sign_data' => 'e62f462112d6a338de7055fd3a9fe24d',
		  'timestamp' => '20190104215817',
		  'trade_date' => '2019-01-04 21:58:17',
		  'trade_status' => '0',
		); */
		
        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['order_id'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['plat_order_id'])
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = strtolower($p['sign_data']);
        
		$sign2 = $this->getSign2($p);
		

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['trade_status'] !== '0'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'{"responseCode": "0000"}');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}